import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
import 'package:flutter/cupertino.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:rs10000/utils/storage.dart';
import 'dart:typed_data';
import '../widgets/dialog.dart';

/*
qr_flutter: ^4.1.0
* */

class QRCode {

  //生成二维码
  static QrImageView qrImage(String content, double size) {
    return QrImageView(data: content, size: size);
  }


  //保存二维码到相册
  static Future<String?> saveQRCode(GlobalKey globalKey, double size) async {
    // 等待当前帧结束，确保布局完成
    await Future.delayed(Duration(milliseconds: 100));

    Uint8List pngBytes = await getPngBytesFromBoundary(globalKey);
    String? err = await Storage.saveImageToGallery(pngBytes, 'qr_code.png');
    if (err != null) {
      print('[B] $err');
      MyDialog.tip(err);
    }else{
      MyDialog.tip('二维码已保存到相册');
    }
  }

  static Future<Uint8List> getPngBytesFromBoundary(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    double pixelRatio = MediaQuery.of(globalKey.currentContext!).devicePixelRatio;
    ui.Image image = await boundary.toImage(pixelRatio: pixelRatio);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    return byteData!.buffer.asUint8List();
  }

}
